package com.capgemini.remind.service;

import com.capgemini.commons.HttpSMSProcessUtil;
import com.capgemini.commons.IdUtils;
import com.capgemini.commons.LicenseUtil;
import com.capgemini.commons.VelocityUtils;
import com.capgemini.core.BaseException;
import com.capgemini.core.PageList;
import com.capgemini.remind.mapper.RemindSendInfoMapper;
import com.capgemini.remind.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author
 * @date
 */
@Service
@Transactional
public class RemindSendInfoService {
    public final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RemindSendInfoMapper remindSendInfoMapper;
    @Autowired
    private RemindSmsService remindSmsService;

    @Autowired
    private HqPromotionService hqPromotionService;
    @Autowired
    private CustomerPromotionService customerPromotionService;
    @Autowired
    private CommonsService commonsService;

    public void queryPage(final PageList<RemindSendInfo> pageList) {
        pageList.setItems(remindSendInfoMapper.queryPage(pageList));
    }

    public int batchInsert(List<RemindSendInfo> list) {
        return remindSendInfoMapper.batchInsert(list);
    }


    public void createRemindSMS(RemindSmsReview remindSmsReview, List<Remind> sendRemindList){
        if(StringUtils.isBlank(remindSmsReview.getMaintenanceItem())){

            //保养类型为全部时按不同保养类型生成短信
            List<String> serviceRemindItems = commonsService.queryByCodeValueGroupByType("ServiceRemindEnabled");
            for (String serviceRemindItem : serviceRemindItems) {
                remindSmsReview.setMaintenanceItem(serviceRemindItem);

                List<Remind> remindList = new ArrayList<Remind>();
                for (Remind tmp : sendRemindList) {
                    if(StringUtils.equalsIgnoreCase(serviceRemindItem, tmp.getMaintenanceItem())){
                        remindList.add(tmp);
                    }
                }

                //促销类型为总部促销时自动匹配
                if(StringUtils.equalsIgnoreCase("1", remindSmsReview.getPromotionType())){
                    HqPromotion hqPromotion = hqPromotionService.getSelectedByMaintenanceType(serviceRemindItem);
                    if(hqPromotion != null){
                        remindSmsReview.setHqPromotionId(hqPromotion.getId().toString());
                    }
                }

                if(!remindList.isEmpty()){
                    sendSMS(remindSmsReview, remindList);
                }
            }
        }else{
            sendSMS(remindSmsReview, sendRemindList);
        }
    }

    private void sendSMS(RemindSmsReview remindSmsReview, List<Remind> sendRemindList){
        //总部促销需生成优惠券
        if(StringUtils.equalsIgnoreCase("1", remindSmsReview.getPromotionType()) && StringUtils.isNotBlank(remindSmsReview.getHqPromotionId())){
            for (Remind remind : sendRemindList) {
                String sms = getSmsContent(remindSmsReview, false, remind.getCustomerId(), true);
                remindSmsReview.setSmsContent(sms);
                List<Remind> tempList = new ArrayList<Remind>();
                tempList.add(remind);
                batchSendSms(tempList, remindSmsReview);
            }
        }else{
            String sms = getSmsContent(remindSmsReview, false, null, false);
            remindSmsReview.setSmsContent(sms);
            batchSendSms(sendRemindList, remindSmsReview);
        }
    }


    public void batchSendSms(List<Remind> remindList, RemindSmsReview remindSmsReview){
        List<RemindSendInfo> list = new ArrayList<RemindSendInfo>();

        Date now = new Date();
        for (Remind remind : remindList) {
            RemindSendInfo tmp = new RemindSendInfo();

            tmp.setId(IdUtils.getNewId());
            tmp.setSmsSendFlag(false);

            tmp.setSmsContent(remindSmsReview.getSmsContent());
            tmp.setPromotionType(remindSmsReview.getPromotionType());
            tmp.setHqPromotionId(remindSmsReview.getHqPromotionId());
            tmp.setCustomerPromotionId(remindSmsReview.getCustomerPromotionId());

            tmp.setDealerNum(remindSmsReview.getDealerNum());
            tmp.setCustomerId(remind.getCustomerId());
            tmp.setMobilePhone(remind.getMobilePhone());
            tmp.setCustomerName(remind.getMemberName());
            tmp.setVehicleId(remind.getCarId());
            tmp.setCarPlate(remind.getCarPlate());
            tmp.setMaintenanceItem(remind.getMaintenanceItem());
            tmp.setServiceRemindId(remind.getServiceRemindId());
            tmp.setCarBrand(remind.getCarBrand());
            tmp.setCarModel(remind.getCarModel());
            tmp.setLastMaintenanceStore(remind.getLastMaintenanceStore());
            tmp.setLastMaintenanceDate(remind.getLastMaintenanceDate());
            tmp.setLastMaintenanceMileage(remind.getLastMaintenanceMileage());
            tmp.setLastPartBrand(remind.getLastPartBrand());
            tmp.setLastPartName(remind.getLastPartName());
            tmp.setLastCarcheckStore(remind.getLastCarcheckStore());
            tmp.setLastCarcheckDate(remind.getLastCarcheckDate());
            tmp.setLastCarcheckMileage(remind.getLastCarcheckMileage());
            tmp.setLastCalcDate(remind.getLastCalcDate());
            tmp.setNextCalcBasis(remind.getNextCalcBasis());
            tmp.setNextCalcDate(remind.getNextCalcDate());
            tmp.setNextCalcMileage(remind.getNextCalcMileage());
            tmp.setMaintenanceSpecBasis(remind.getMaintenanceSpecBasis());
            tmp.setCreateBy("0");
            tmp.setCreateDate(now);

            list.add(tmp);
        }
//        batchInsert(list);

        int beginIndex = 0;
        while (beginIndex < list.size()){

            int endIndex = 2000;
            if(list.size() - beginIndex < 2000){
                endIndex = list.size() - beginIndex;
            }

            List sub = list.subList(beginIndex,  beginIndex + endIndex);
            List two = new ArrayList(sub);
            batchInsert(two);
            two.clear();

            beginIndex += endIndex;
        }

        //扣除短信余额
//        remindSmsService.subtractSmsQuotaByDealerNum(list.size(), remindSmsReview.getDealerNum());

        //更新对应门店的保养提醒项目的最后提醒时间
//        remindSendInfoMapper.refreshLastRemindInfo(remindSmsReview.getDealerNum());

        //todo 批量发送短信，目前短信通道支持一条短信同时发送至1000个手机号码
        int index = 0;
        List<String> mobileList = new ArrayList<String>();
        List<String> idList = new ArrayList<String>();
        for (RemindSendInfo remindSendInfo : list) {
            mobileList.add(remindSendInfo.getMobilePhone());
            idList.add(remindSendInfo.getId());
            index ++;
            if(index % 999 == 0){
                //发送短信
                String smsBatchId = HttpSMSProcessUtil.sendMessage(remindSmsReview.getSmsContent(), mobileList);
                remindSendInfoMapper.updateSmsBatchIdByIds(smsBatchId, idList);
                index = 0;
                mobileList.clear();
                idList.clear();
            }
        }

        if(index > 0){
            //发送短信
            String smsBatchId = HttpSMSProcessUtil.sendMessage(remindSmsReview.getSmsContent(), mobileList);
            remindSendInfoMapper.updateSmsBatchIdByIds(smsBatchId, idList);
        }


    }


    public String getSmsContent(RemindSmsReview remindSmsReview, boolean isHighlighting, String customerId, boolean isCreateCoupon){
        SmsTemplate smsTemplate = commonsService.queryBySmsTemplateByCode("SendRemindMsgTemplateNo2");
        DealerInfo dealerInfo = commonsService.getDealerInfoByDealerNum(remindSmsReview.getDealerNum());

        Map param = new HashMap();

        if(dealerInfo != null){
            param.put("dealerNum", dealerInfo.getDealerNum());
            param.put("dealerName", dealerInfo.getDealerName());
            param.put("dealerAlias", dealerInfo.getAlias());
            param.put("dealerAddress", dealerInfo.getAddress());
            param.put("dealerPhoneNum", dealerInfo.getTelPhone());
        }
        String begin = "";
        String end = "";

        if(isHighlighting){
            begin = "<span class='highlighting'>";
            end = "</span>";
        }
        if(StringUtils.isBlank(remindSmsReview.getMaintenanceItem())){
            remindSmsReview.setMaintenanceItem("${保养类型}");
        }

        param.put("serviceType",  begin + remindSmsReview.getMaintenanceItem() + end);

        //促销信息

	        if(StringUtils.equalsIgnoreCase("1", remindSmsReview.getPromotionType()) && StringUtils.isNotBlank(remindSmsReview.getHqPromotionId())){//总部促销
	            HqPromotion hqPromotion = hqPromotionService.getById(remindSmsReview.getHqPromotionId());
	            if(hqPromotion != null){
	                String couponNumber = "CJ888888XX";
                    if(isCreateCoupon){
                        couponNumber = createCouponByBatchLineId(hqPromotion.getCouponBatchLineId(), customerId, hqPromotion);
                    }
	                param.put("promotion", begin + hqPromotion.getSmsText(couponNumber) + end);

	            }
	        }else if(StringUtils.equalsIgnoreCase("2", remindSmsReview.getPromotionType())){//自定义促销
	            CustomerPromotion customerPromotion = customerPromotionService.getById(remindSmsReview.getCustomerPromotionId());
	            if(customerPromotion != null) {
	                param.put("promotion", begin + customerPromotion.getSmsText() + end);
	            }
	        }

        String sms = null;
        try {
            sms = VelocityUtils.merge(smsTemplate.getMessageContent(), param);
        } catch (Exception e) {
            log.error("", e);
        }

        return sms;
    }


    /**
     *
     * 根据市场活动批次优惠券行的id， MarsCustomerId，总部促销 生成优惠券信息
     *
     * @param couponBatchLineId
     * @param customerId
     * @param hqPromotion
     * @return
     */
    public String createCouponByBatchLineId(Long couponBatchLineId, String customerId, HqPromotion hqPromotion){
        CouponBatchLineInfo  couponBatchLineInfo = remindSendInfoMapper.getCouponBatchLineInfoById(couponBatchLineId);

        String couponNumber = "CJ" + LicenseUtil.getLicense8(couponBatchLineId);
        if(couponBatchLineInfo == null){
            throw new BaseException("16005", "参数错误");
        }

        CouponInfo couponInfo = new CouponInfo();
        Calendar calendar = Calendar.getInstance();
        if(hqPromotion != null){
            if(StringUtils.equalsIgnoreCase("day", hqPromotion.getTimeUnit())){
                calendar.add(Calendar.DAY_OF_MONTH, hqPromotion.getPeriodOfValidity().intValue());
            }else if(StringUtils.equalsIgnoreCase("month", hqPromotion.getTimeUnit())){
                calendar.add(Calendar.MONTH, hqPromotion.getPeriodOfValidity().intValue());
            }else if(StringUtils.equalsIgnoreCase("year", hqPromotion.getTimeUnit())){
                calendar.add(Calendar.YEAR, hqPromotion.getPeriodOfValidity().intValue());
            }else{
                calendar.add(Calendar.MONTH, 3);
            }
        }else{
            calendar.add(Calendar.MONTH, 3);
        }

        couponInfo.setCouponNumber(couponNumber);
        couponInfo.setBatchId(couponBatchLineInfo.getBatchId());
        couponInfo.setTicketDefId(couponBatchLineInfo.getTicketDefId());
        couponInfo.setMarsCustomerId(customerId);
        couponInfo.setCreateDate(new Date());
        couponInfo.setDealerNum(couponBatchLineInfo.getDealerNum());

        couponInfo.setEndDate(calendar.getTime());


        remindSendInfoMapper.createCoupon(couponInfo);

        remindSendInfoMapper.updateCouponBatchLine(couponInfo);

        if(couponBatchLineInfo.getTotalNum() != null && couponBatchLineInfo.getTotalNum() > 0){
            remindSendInfoMapper.updateCouponBatchIsGenerated(couponInfo.getBatchId());
        }

        return couponNumber;

    }

}
